<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/9/21
 * Time: 15:15
 */

namespace app\controller\index;


use app\common\lib\Guzzle;
use app\common\lib\YunZhangHu2;
use app\controller\CoreController;
use app\exception\IndexException;
use app\logic\index\novel\OceanengineLogic;
use app\logic\index\pay\PayLogic;
use app\logic\index\pay\WeixinPayLogic;
use app\logic\index\video\VideoLogic;
use app\logic\index\withdraw\TransferLogic;
use support\Request;

class NotifyController extends CoreController
{
    /**
     * 抖音事件推送通知
     * @param Request $request
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function douyinWebHooks(Request $request)
    {
        try{
            $param = $request->input();

            WebHooksLogic::getInstance()->saveWebHooksData($param);

            //file_put_contents(storage_path('douyinWebHooks.log'),json_encode($param)."\n",8);

            return json_encode(($param['content']??[]));
        }catch (IndexException $e){
            return $this->endError($e);
        }
    }

    /**
     * 小程序支付异步回调通知
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wechatPayNotify(Request $request)
    {
        file_put_contents(runtime_path('wechatPayNotify-headers.log'),json_encode(request()->header())."\n",8);
        file_put_contents(runtime_path('wechatPayNotify-body.log'),request()->rawBody()."\n",8);

        $result = WeixinPayLogic::getInstance()->wechatPayNotify();
        return json($result);
    }

    /**
     * gitee事件推送通知
     * @param Request $request
     * @return false|\Illuminate\Http\JsonResponse|string
     */
    public function giteeWebHooks(Request $request)
    {
        $param = $request->all();
        //推送dev分支，自动更新测试环境代码
        if($param['password']=='0fiW3@m4@e05O!7q'){
            if(!empty($param['project']) && $param['project']['full_name']=='xianyu_3/php' && $param['ref']=='refs/heads/dev'){
                exec('/data/script/gitup.sh video',$output);
                file_put_contents(runtime_path('giteeWebHooksVideo.log'),json_encode($output,256)."\n",8);
            }
        }

        return 'success';
    }

    public function transferNotify(Request $request)
    {
        $param = $request->all();
        $data = YunZhangHu2::getInstance()->payStatusNotify($param);
        file_put_contents(runtime_path('yunzhanghu_notify.log'),json_encode($data,256)."\n",8);
        $result = [];
        if($data){
            $result = TransferLogic::getInstance()->transferNotify($data);
        }

        //echo "success";       //回写success，终止本次回调
        return $result ? 'success' : 'fail';
    }

    public function tencentIvldNotify(Request $request)
    {
        $header = $request->header();
        $param = $request->all();

        file_put_contents(runtime_path('tencent_ivld_notify.log'),'header: '.json_encode($header,256)."\n",8);
        file_put_contents(runtime_path('tencent_ivld_notify.log'),'param: '.json_encode($param,256)."\n",8);
        $result = [];

        return $result ? 'success' : 'fail';
    }

    /**
     * 苹果异步回调通知
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws IndexException
     */
    public function applePayNotify(Request $request)
    {
        $postDataContent = $request->rawBody();
        file_put_contents(runtime_path('apple_pay_notify.log'),$postDataContent);
        $result = PayLogic::getInstance()->applePayNotify($postDataContent);

        return $this->endSuccess($result);
    }

    /**
     * 飞书订阅时间回调通知
     * @param Request $request
     * @return \support\Response
     * @throws \Exception
     */
    public function feishuEventNotify(Request $request)
    {
        $param = $request->all();
        file_put_contents(runtime_path('feishu_event_notify.log'), json_encode($param,256)."\n", 8);


        if($param['header']['event_type']=='contact.user.created_v3' && $param['header']['token']=='pLRIIYVANTgKPlSVLnrj2K2R714SVmy3'){
            $user = $param['event']['object']??[];
            $apiParam = [
                'receive_id'=>'oc_ea62eaaf664cce8b500101fb0a7347c6',
                'content'=>'{
  "config": {
    "wide_screen_mode": true
  },
  "header": {
    "title": {
      "tag": "plain_text",
      "content": "🎁 '.($user['name']??'').'同学，欢迎您加入新希望！"
    },
    "template": "Green"
  },
  "elements": [
    {
      "tag": "img",
      "img_key": "img_v2_bbe23110-2475-428e-9ca8-1bd8cebda7fg",
      "alt": {
        "tag": "plain_text",
        "content": ""
      }
    },
    {
      "tag": "div",
      "text": {
        "tag": "lark_md",
        "content": "🥰 亲爱的[@'.($user['name']??'').'](https://www.feishu.cn)同学，您好：\n首先欢迎您加入**「新希望集团」**，这里是一些新人必学技巧，请您查收！\n\n🏼 **您的直属Leader**：[@郑浩](https://www.feishu.cn)，他会给你最直接的帮助！\n\n☎️ 欢迎点击下方按钮，了解更多企业内容，如有更多疑问，可联系HR值班号！"
      }
    },
    {
      "tag": "action",
      "actions": [
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "立即查看详情"
          },
          "url": "https://bytedance.feishu.cn/",
          "type": "primary"
        },
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "联系HR值班号"
          },
          "url": "https://bytedance.feishu.cn/",
          "type": "default"
        }
      ]
    }
  ]
}',
                "msg_type"=>"interactive",
            ];
            $header = [
                'Authorization'=>'Bearer t-g1045fbFOILXP5BCNIKVCVOIOBV34QWJMRZGWJ3K',
            ];
            $result = Guzzle::post('https://open.feishu.cn/','open-apis/im/v1/messages?receive_id_type=chat_id',$apiParam,$header,'json');
           //var_dump(Guzzle::getError());
            return json($result);
        }

        return json(['challenge'=>$param['challenge']??'']);
    }


    /**
     * 巨量引擎授权回调
     */
    public function getOceanengineAuthCode(Request $request)
    {
        try{
            file_put_contents(runtime_path('getOceanengineAuthCode.log'), json_encode($request->all(),256));
            $param['auth_code'] = $request->input('auth_code');

            $res = OceanengineLogic::getInstance()->getTokenByAuthCode($param['auth_code']);

            return $this->endSuccess($res);
        }catch (IndexException $e){
            return $this->endError($e);
        }
    }

    /**
     * 巨量引擎广告检测有效触电
     */
    public function getOceanengineDetectionLink(Request $request)
    {
        try{
            file_put_contents(runtime_path('getOceanengineDetectionLink.log'), date('Y-m-d H:i:s').": ".json_encode($request->all(),256)."\n",FILE_APPEND);

            $res = OceanengineLogic::getInstance()->getOceanengineDetectionLink($request->all());
            return $this->endSuccess([]);
        }catch (IndexException $e){
            return $this->endError($e);
        }
    }


}
